import { FormDialog, FormLayout, FormItem, Input, Password, Select } from '@formily/element'
import { createSchemaField } from '@formily/vue'
import { action } from '@formily/reactive'
import { ObjectGroupApi } from '../../api/object-group'

const groupApi = new ObjectGroupApi;
const useObjectGroupDataSource = (service) => (field) => {
    field.loading = true
    service(field).then(
        action.bound((data) => {
            field.dataSource = data
            field.loading = false
        })
    )
}
const loadObjectGroup = async (field) => {
    const data = await groupApi.findList({ order: [['sort']] });
    return new Promise((resolve) => {
        resolve(data.data.map(({ id, name }) => ({ label: name, value: `${id}^${name}` })))
    });
}

const { SchemaField } = createSchemaField({
    components: {
        FormItem,
        Input,
        Select,
        Password,
    },
    scope: {
        useObjectGroupDataSource,
        loadObjectGroup
    }
})

// 弹框表单组件
export const InputForm = {
    data() {
        const schema = {
            type: 'object',
            properties: {
                name: {
                    type: 'string',
                    title: '名称',
                    required: true,
                    'x-decorator': 'FormItem',
                    'x-component': 'Input',
                    'x-component-props': {
                        size: 'small'
                    }
                },
                phone_num: {
                    type: 'string',
                    title: '电话号码',
                    required: true,
                    'x-decorator': 'FormItem',
                    'x-component': 'Input',
                    'x-component-props': {
                        size: 'small'
                    }
                },
                group_info: {
                    type: 'string',
                    title: '所属单位',
                    required: true,
                    'x-decorator': 'FormItem',
                    'x-component': 'Select',
                    'x-component-props': {
                        size: 'small'
                    },
                    'x-reactions': ['{{useObjectGroupDataSource(loadObjectGroup)}}'],
                },
                group_id: {
                    type: 'string',
                    hidden: true,
                },
                group_name: {
                    type: 'string',
                    hidden: true,
                }

            },
        }
        return {
            schema,
        }
    },
    render(h) {
        return (
            <FormLayout labelCol={6} wrapperCol={10}>
                <SchemaField schema={this.schema} />
                <FormDialog.Footer>
                </FormDialog.Footer>
            </FormLayout>
        )
    },
}